package com.daxue.lcm.api.grpc.config;

import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;

/**
 * @author daxue0929
 * @date 2022/9/28
 */

public class GrpcClientInterceptor implements ClientInterceptor {
    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next
    ) {
        return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
            @Override
            public void start(ClientCall.Listener<RespT> responseListener, Metadata headers) {
                processMDC(headers);
                super.start(responseListener, headers);
            }
        };
    }

    private void processMDC(final Metadata headers) {



        // todo...
//        final Map<String, String> mdc = MDC.getCopyOfContextMap();
//        if (mdc == null) {
//            log.trace("MDC is null in grpc client side, all headers: {}", headers.toString());
//            return;
//        }
//        try {
//            headers.put(MDC_HEADER_KEY, asString(mdc));
//        } catch (JsonProcessingException e) {
//            log.error("Writing MDC failed in grpc client side");
//        }
    }

}
